/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2012 www.pretty-tools.com
 */

var gUserProfile = new Array();
var gRuleTree, gRuleTreeView, gRuleTreeContentView;
var gSaveRules = false;

function initRuleTree()
{
    try
    {
        // init global data
        gRuleTree = document.getElementById("rules_tree");
        gRuleTreeView = gRuleTree.view;
        gRuleTreeContentView = gRuleTree.contentView;
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("Exception initRuleTree: " + ex);
    }
}

function createDomainElements(idx, domain)
{
    var treecell = document.createElement("treecell");
    treecell.setAttribute("label", domain);

    var treerow = document.createElement("treerow");
    treerow.appendChild(treecell);

    var domainItem = document.createElement("treeitem");
    domainItem.setAttribute("id", "domain_"+idx);
    domainItem.setAttribute("container", "true");
    domainItem.setAttribute("open", "true");
    domainItem.setAttribute("domain_idx", idx);
    domainItem.appendChild(treerow);

    return domainItem;
}

function getPagePatternLabel(page)
{
    return page.pattern.source;
}

function getElementPatternLabel(page)
{
    return page.elementTag + ": " + page.elementPattern.source;
}

function createPageElements(domainIndex, pageIndex, page)
{
    var treerow = document.createElement("treerow");

    var treecell;
    // empty cell
    treerow.appendChild(document.createElement("treecell"));
    // page pattern
    treerow.appendChild(treecell = document.createElement("treecell"))
    if (page.disabled || !page.supported) treecell.setAttribute("properties", "disabled_rule");
    treecell.setAttribute("label", getPagePatternLabel(page));
    // element pattern
    treerow.appendChild(treecell = document.createElement("treecell"))
    if (page.disabled || !page.supported) treecell.setAttribute("properties", "disabled_rule");
    treecell.setAttribute("label", getElementPatternLabel(page));

    var treeitem = document.createElement("treeitem");
    treeitem.setAttribute("id", "domain_"+domainIndex+"_page_"+pageIndex);
    treeitem.setAttribute("domain_idx", domainIndex);
    treeitem.setAttribute("page_idx", pageIndex);
    treeitem.appendChild(treerow);

    return treeitem;
}

function createRuleElements(idx, item, rules_treechildren)
{
    if (!rules_treechildren)
        rules_treechildren = document.getElementById("rules_treechildren");

    var domainTreeRow = createDomainElements(idx, item.domain);
    var treechildren = document.createElement("treechildren");
    treechildren.setAttribute("id", "domain_"+idx+"_children");
    for (var p in item.pages)
    {
        var page = item.pages[p];
        if (page) // skip null
            treechildren.appendChild(createPageElements(idx, p, page));
    }
    domainTreeRow.appendChild(treechildren)
    rules_treechildren.appendChild(domainTreeRow);
}

function appendRuleElements(idx, treeitem)
{
    document.getElementById("domain_"+idx+"_children").appendChild(treeitem);
}

function updateUserRules()
{
    try
    {
        var rules_treechildren = document.getElementById("rules_treechildren");
        // remove old
        while (rules_treechildren.hasChildNodes())
        {
            rules_treechildren.removeChild(rules_treechildren.childNodes[0]);
        }

        for (var i in gUserProfile)
        {
            createRuleElements(i, gUserProfile[i], rules_treechildren);
        }

        updateButtons();
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("Exception updateUserRules: " + ex);
    }
}

function getTreeCurrentIndexOrFail()
{
    var idx = gRuleTree.currentIndex;
    if (idx >= 0 && idx < gRuleTreeView.rowCount)
        return idx;

    throw "Invalid index";
}

function countPages(pages)
{
    if (!pages || !pages.length)
        return 0;

    var count = 0;
    for (var p in pages)
    {
        if (pages[p]) // skip null
            ++count;
    }
    return count;
}

function findDomainIndex(domain)
{
    for (var i in gUserProfile)
    {
        if (gUserProfile[i] && gUserProfile[i].domain == domain)
            return i;
    }

    if (gLogger.enabled) gLogger.debug("findDomainIndex: Domain not found " + domain);
    return -1;
}

function isSingleRuleInDomain(idx)
{
    try
    {
        var treeitem = gRuleTreeContentView.getItemAtIndex(idx);
        if (!treeitem.hasAttribute("domain_idx"))
            throw "Invalid item.";

        return countPages(gUserProfile[1*treeitem.getAttribute("domain_idx")].pages) <= 1;
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("Exception isSingleRuleInDomain: " + ex);
    }
    return true;
}

function selectTreeNode(idx)
{
    gRuleTreeView.selection.select(idx);

    var boxobject = gRuleTree.boxObject;
    boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
    boxobject.ensureRowIsVisible(idx);
}

function updateRow(idx, page)
{
    var columns = gRuleTree.columns;

    gRuleTreeView.setCellText(idx, columns.getNamedColumn("col_page_pattern"), getPagePatternLabel(page));
    gRuleTreeView.setCellText(idx, columns.getNamedColumn("col_element_pattern"), getElementPatternLabel(page));

    if (!page.disabled && page.supported)
    {
        var treeitem = gRuleTreeContentView.getItemAtIndex(idx);
        for (var i in treeitem.childNodes)
        {
            var treerow = treeitem.childNodes[i];
            for (var j in treerow.childNodes)
            {
                if (treerow.childNodes[j].tagName != "treecell")
                    continue;

                if (treerow.childNodes[j].hasAttribute("properties"))
                    treerow.childNodes[j].setAttribute("properties", "");
            }
        }
    }
}

function updateDomain(idx, domain)
{
    gRuleTreeView.setCellText(idx, gRuleTree.columns.getNamedColumn("col_domain"), domain);
}

function removeRule()
{
    try
    {
        //TODO: think about confirmation... (add 'force' parameter if confirmation)

        var idx = getTreeCurrentIndexOrFail();

        var treeitem = gRuleTreeContentView.getItemAtIndex(idx);
        if (!treeitem.hasAttribute("domain_idx"))
            throw "Invalid item. no 'domain_idx' attribute";

        var domainIndex = 1*treeitem.getAttribute("domain_idx");
        if (gRuleTreeView.isContainer(idx))
        {
            if (gLogger.enabled) gLogger.debug("removeRule: Remove all rules for domain idx = " + domainIndex);

            gUserProfile[domainIndex] = null;
            treeitem.parentNode.removeChild(treeitem);
        }
        else
        {
            if (!treeitem.hasAttribute("page_idx"))
                throw "Invalid item. no 'page_idx' attribute";

            var pageIndex = 1*treeitem.getAttribute("page_idx");
            if (gLogger.enabled) gLogger.debug("removeRule: Remove rules idx = " + pageIndex);

            gUserProfile[domainIndex].pages[pageIndex] = null;
            gUserProfile[domainIndex].checksum = null;
            // check rules count now
            if (countPages(gUserProfile[domainIndex].pages) > 0)
                treeitem.parentNode.removeChild(treeitem);
            else // remove parent
            {
                gUserProfile[domainIndex] = null; // reset domain

                var parentIndex = gRuleTreeView.getParentIndex(idx);
                var parentTreeItem = gRuleTreeContentView.getItemAtIndex(parentIndex);
                // remove parent
                parentTreeItem.parentNode.removeChild(parentTreeItem);
            }
        }
        gSaveRules = true;

        if (gRuleTreeView.rowCount > 0) selectTreeNode(idx > 0 ? idx-1 : 0);

        updateButtons();
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("removeRule: ", ex);
    }
}

function isFirstRule(treeitem)
{
    return !treeitem.previousSibling;
}

function isLastRule(treeitem)
{
    return !treeitem.nextSibling;
}
